using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Newtonsoft.Json;

namespace GameOverlayWPF
{
    public partial class PublishSchemeWindow : Window
    {
        private readonly bool _isAobMode;
        private readonly DatabaseManager _dbManager;
        private readonly HttpClient _httpClient;

        public PublishSchemeWindow(bool isAobMode)
        {
            InitializeComponent();
            _isAobMode = isAobMode;
            _dbManager = DatabaseManager.Instance;
            _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };

            // 如果是全面战场模式，隐藏价格字段
            if (_isAobMode)
            {
                PriceLabel.Visibility = Visibility.Collapsed;
                PriceBox.Visibility = Visibility.Collapsed;
            }

            LoadCategoriesAsync();
        }

        private async void LoadCategoriesAsync()
        {
            try
            {
                List<string> categories;
                if (_isAobMode)
                {
                    categories = await _dbManager.GetCategoriesAobAsync();
                }
                else
                {
                    categories = await _dbManager.GetCategoriesAsync();
                }

                CategoryBox.ItemsSource = categories;
            }
            catch (Exception ex)
            {
                ShowError($"加载武器分类失败: {ex.Message}");
            }
        }

        private async void CategoryBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var selectedCategory = CategoryBox.SelectedItem as string;
            if (!string.IsNullOrEmpty(selectedCategory))
            {
                await LoadWeaponsAsync(selectedCategory);
            }
        }

        private async Task LoadWeaponsAsync(string category)
        {
            try
            {
                List<string> weapons;
                if (_isAobMode)
                {
                    weapons = await _dbManager.GetWeaponsAobAsync(category);
                }
                else
                {
                    weapons = await _dbManager.GetWeaponsAsync(category);
                }

                WeaponNameBox.ItemsSource = weapons;
                WeaponNameBox.IsEnabled = true;
            }
            catch (Exception ex)
            {
                ShowError($"加载武器列表失败: {ex.Message}");
            }
        }

        private void PriceBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 只允许输入数字
            e.Handled = !Regex.IsMatch(e.Text, "^[0-9]+$");
        }

        private async void PublishBtn_Click(object sender, RoutedEventArgs e)
        {
            ErrorText.Visibility = Visibility.Collapsed;

            // 验证必填字段
            if (string.IsNullOrWhiteSpace(DescriptionBox.Text))
            {
                ShowError("请输入方案描述");
                return;
            }

            if (CategoryBox.SelectedItem == null)
            {
                ShowError("请选择武器分类");
                return;
            }

            if (WeaponNameBox.SelectedItem == null)
            {
                ShowError("请选择武器名称");
                return;
            }

            if (string.IsNullOrWhiteSpace(SchemeBox.Text))
            {
                ShowError("请输入方案配置代码");
                return;
            }

            // 验证价格（仅烽火地带）
            int? price = null;
            if (!_isAobMode)
            {
                if (string.IsNullOrWhiteSpace(PriceBox.Text))
                {
                    ShowError("请输入价格");
                    return;
                }

                if (!int.TryParse(PriceBox.Text, out int priceValue) || priceValue < 1 || priceValue > 999)
                {
                    ShowError("价格必须是1-999之间的数字");
                    return;
                }

                price = priceValue;
            }

            // 禁用发布按钮，防止重复提交
            PublishBtn.IsEnabled = false;
            PublishBtn.Content = "发布中...";

            try
            {
                await PublishSchemeAsync(
                    DescriptionBox.Text.Trim(),
                    CategoryBox.SelectedItem.ToString()!,
                    WeaponNameBox.SelectedItem.ToString()!,
                    SchemeBox.Text.Trim(),
                    price
                );

                MessageBox.Show("方案发布成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
                PublishBtn.IsEnabled = true;
                PublishBtn.Content = "发布";
            }
        }

        private async Task PublishSchemeAsync(string description, string category, string weaponName, string scheme, int? price)
        {
            // 获取当前用户信息
            var user = AuthService.GetCurrentUser();
            if (user == null)
            {
                throw new Exception("用户未登录");
            }

            // 构建请求数据
            var requestData = new Dictionary<string, object>
            {
                { "description", description },
                { "category", category },
                { "weaponName", weaponName },
                { "scheme", scheme }
            };

            if (price.HasValue)
            {
                requestData["price"] = price.Value;
            }

            // 编码用户信息
            var userInfo = new { id = user.Id, username = user.Username };
            var userInfoJson = JsonConvert.SerializeObject(userInfo);
            var base64UserInfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(userInfoJson));

            // 选择API端点
            var endpoint = _isAobMode ? "schemes_aob" : "schemes";
            var url = $"https://maqt.top/api/{endpoint}";

            // 发送请求
            var json = JsonConvert.SerializeObject(requestData);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            _httpClient.DefaultRequestHeaders.Clear();
            _httpClient.DefaultRequestHeaders.Add("x-user-info", base64UserInfo);

            var response = await _httpClient.PostAsync(url, content);
            var responseText = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                // 解析错误响应
                try
                {
                    var errorResponse = JsonConvert.DeserializeObject<PublishErrorResponse>(responseText);
                    if (errorResponse?.SensitiveWords != null && errorResponse.SensitiveWords.Count > 0)
                    {
                        throw new Exception($"内容包含敏感词: {string.Join(", ", errorResponse.SensitiveWords)}");
                    }
                    throw new Exception(errorResponse?.Message ?? "发布失败");
                }
                catch (JsonException)
                {
                    throw new Exception($"发布失败: {response.StatusCode}");
                }
            }
        }

        private void ShowError(string message)
        {
            ErrorText.Text = message;
            ErrorText.Visibility = Visibility.Visible;
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private void CloseBtn_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }

    // 发布响应模型
    public class PublishErrorResponse
    {
        [JsonProperty("success")]
        public bool Success { get; set; }

        [JsonProperty("message")]
        public string? Message { get; set; }

        [JsonProperty("sensitiveWords")]
        public List<string>? SensitiveWords { get; set; }
    }
}
